package com.shxzz.shortlink.project.common.convention.result;


import com.shxzz.shortlink.project.common.convention.errorcode.BaseErrorCode;
import com.shxzz.shortlink.project.common.convention.exception.BaseException;

import java.util.Optional;

/**
 * @author shxzz
 * @create 2023-12-08-18:48
 * @description 统一返回对象构建类
 */
public class Results {
    private static final String SUCCESS_CODE = "0";

    private Results() {
    }

    /**
     * 构建成功响应
     */
    public static Result<Void> success() {
        return new Result<Void>()
                .setCode(SUCCESS_CODE)
                .setMsg("请求成功");
    }

    /**
     * 构建带返回数据的成功响应
     */
    public static <T> Result<T> success(T data) {
        return new Result<T>()
                .setCode(SUCCESS_CODE)
                .setMsg("请求成功")
                .setData(data);
    }

    /**
     * 基于 {@link BaseException} 构建失败响应
     */
    public static Result<Void> failure(BaseException exception) {
        String code = Optional.ofNullable(exception.getErrorCode())
                .orElse(BaseErrorCode.SERVICE_ERROR.getCode());

        String msg = Optional.ofNullable(exception.getErrorMsg())
               .orElse(BaseErrorCode.SERVICE_ERROR.getMsg());

        return new Result<Void>()
                .setCode(code)
                .setMsg(msg);
    }

    /**
     * 构建默认失败响应
     */
    public static Result<Void> failure() {
        return new Result<Void>()
                .setCode(BaseErrorCode.SERVICE_ERROR.getCode())
                .setMsg(BaseErrorCode.SERVICE_ERROR.getMsg());
    }

    /**
     * 根据 code 和 message 构建失败响应
     */
    public static Result<Void> failure(String code, String msg) {

        return new Result<Void>()
               .setCode(code)
               .setMsg(msg);
    }
}
